package com.chihuo.resource;

import java.net.URI;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.chihuo.bussiness.Category;
import com.chihuo.dao.CategoryDao;

@Path("/categories")
public class CategoriesResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;

	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,
			MediaType.TEXT_XML })
	public List<Category> getCategories() {
		CategoryDao dao = new CategoryDao();
		List<Category> list = dao.findAll();
		return list;
	}
	
	@Path("{id}")
	public CategoryResource getCategoryResource(@PathParam("id") int id) {
		return new CategoryResource(uriInfo, request, id);
	}
	
	@POST
	@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public Response createCategory(JAXBElement<Category> c) {
		Category newCatagory = c.getValue();
		CategoryDao dao = new CategoryDao();
		Category createdCategory = dao.saveOrUpdate(newCatagory);
		return Response.created(URI.create(createdCategory.getId() + "")).build();
	}
	
	@GET
	@Path("count")
	@Produces(MediaType.TEXT_PLAIN)
	public String getCount() {
		CategoryDao dao = new CategoryDao();
		return String.valueOf(dao.findAll().size());
	}

//	@GET
//	@Path("{id}")
//	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,
//		MediaType.TEXT_XML })
//	public List<Recipe> get(@PathParam("id") int id) {
//		RecipeDao dao = new RecipeDao();
//		List<Recipe> list = dao.findByCategory(id);
//		return list;
//	}
}
